//
//  ICTCustomURLCache.h
//  WDWebViewCache
//
//  Created by  WangDan on 16/3/14.
//  Copyright © 2016年 iCareTech. All rights reserved.
//

#import "TCBanner.h"
#import <UIImageView+WebCache.h>
#import "UIColor+ICT.h"
#import "TCConfiguration.h"
#import "UIView+YWK.h"


static const int kTagBanner = 300; //广告位内容tag前缀

@interface TCBanner ()<UIScrollViewDelegate>

@property (nonatomic)           NSInteger       pageCount;            //banner滚动页面个数
@property (nonatomic, strong)   NSTimer         *timer;               //自动滚动定时器

@property (nonatomic, strong)   UIPageControl   *pageControll;

@property (nonatomic, assign)   CGFloat         bannerWidth;
@property (nonatomic, assign)   CGFloat         bannerHeight;

 //插入首尾图片，实现循环滚动。如：传递来的数组参数是[1,2,3]，moreImgUrls存储[3,1,2,3,1]。
@property (nonatomic, copy)     NSMutableArray  *contentViews;

//点击banner跳转的URL，保持与banner图片数组对应，包括插入和移除元素
@property (nonatomic, copy)     NSMutableArray  *imgContentsMutableArr;

@end

@implementation TCBanner

@synthesize isAutoScroll = _isAutoScroll;
@synthesize hasMonitorResult = _hasMonitorResult;

#pragma mark - life cycle

- (instancetype)initWithMonitorResultAndFrame:(CGRect)frame{
    
    if (self = [super initWithFrame:frame]) {
        
        self.backgroundColor = kYWKBackGroundColor;
        _bannerWidth = frame.size.width;
        _bannerHeight = frame.size.height;
        _hasMonitorResult = NO;
        
        _timer = [NSTimer scheduledTimerWithTimeInterval:3.0
                                                  target:self
                                                selector:@selector(timerTriggerAutoScroll)
                                                userInfo:nil
                                                 repeats:YES];
        
        [self.layer removeAnimationForKey:@"kDeatilAnimation"];         //去除动画，使用自定义转场动画
        self.bounces = NO;
        self.showsVerticalScrollIndicator = NO;
        self.showsHorizontalScrollIndicator = NO;
        self.pagingEnabled = YES;
        self.delegate = self;
        self.scrollsToTop = NO;
        self.directionalLockEnabled = YES;
    }
    
    return self;
}

- (void)dealloc{
    
    [self.timer invalidate];
    self.timer = nil;
    
}

#pragma mark - public methods

- (void)addBanner:(UIView *)parentView withImgUrls:(NSArray *) imgUrls isAutoScroll:(BOOL) autoScroll{
    
    _pageCount = self.hasMonitorResult ? imgUrls.count + 1 : imgUrls.count;
    _isAutoScroll = autoScroll;
    
    [self configContentItemsWithImgViews:[self contentImageViewsByImageURLs:imgUrls]];
    
    self.contentSize = CGSizeMake(self.contentViews.count * self.bannerWidth, 0);
    self.contentOffset = CGPointMake(self.pageCount > 1 ? self.bannerWidth : 0, 0);
    
    [self addSubview:[self configContentViewWithViews:self.contentViews]];
    
    [parentView addSubview:self];
    
    [parentView addSubview:self.pageControll];
}

#pragma mark - private methods

/**
 *  根据URL初始化UIImageView，并存入数组；同时将数组ImageUrls原样式【1，2】变为【3，1，2，3,1】样式
 *
 *  @param imageURLs 图片URL
 *
 *  @return NSArray
 */
- (NSArray *)contentImageViewsByImageURLs:(NSArray *) imageURLs{
    
    if (!imageURLs || imageURLs.count == 0) {
        return [NSArray array];
    }
    
    NSMutableArray *imgUrlsMutableArr = imageURLs.mutableCopy;
    _imgContentsMutableArr = self.detailURLs.mutableCopy;
    
    [imgUrlsMutableArr addObject:imageURLs[0]];
    [imgUrlsMutableArr insertObject:imageURLs[imageURLs.count - 1] atIndex:0];
    
    [self.imgContentsMutableArr addObject:self.detailURLs[0]];
    [self.imgContentsMutableArr insertObject:self.detailURLs[self.detailURLs.count - 1] atIndex:0];
    
    NSMutableArray *imgViews = @[].mutableCopy;
    
    [imgUrlsMutableArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj isKindOfClass:[NSString class]]) {
            NSString *imgUrl = (NSString *)obj;
            
            UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0,
                                                                                 0,
                                                                                 self.bannerWidth,
                                                                                 self.bannerHeight)];
            [imgView sd_setImageWithURL:[NSURL URLWithString:imgUrl]];
            [imgViews addObject:imgView];
            
            imgView.userInteractionEnabled = YES;
            imgView.tag = kTagBanner + idx;
            
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                  action:@selector(bannerTap:)];
            [imgView addGestureRecognizer:tap];
        }
        
    }];
    
    return imgViews.copy;
}

/**
 *  将监测结果添加到banner的ContentView中
 *
 *  @param imageViews 根据网络请求而生成的图片数组
 */
- (void)configContentItemsWithImgViews:(NSArray *) imageViews{
    
    NSMutableArray *imgViewMutableArr = imageViews.mutableCopy;
    
    if (imageViews.count == 3) {
            
            //后台只返回一张广告图片时，图片不需要循环滑动，只保留一张
            for (int i = 2; i > 0; i--) {
                
                [imgViewMutableArr removeObjectAtIndex:i];
                
                [self.imgContentsMutableArr removeObjectAtIndex:i];
            }
        }
    self.contentViews = imgViewMutableArr.copy;
    self.detailURLs = self.imgContentsMutableArr.copy;
}

/**
 *  配置banner的ContentView
 *
 *  @param views 组成Contentview的所有Views
 *
 *  @return banner的ContentView
 */
- (UIView *)configContentViewWithViews:(NSArray *) views{
    
    UIView *bannerContentView;
        
        bannerContentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, views.count * self.bannerWidth, self.bannerHeight)];
    
        [views enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            if ([obj isKindOfClass:[UIView class]]) {
                
                UIView *aContentView = (UIImageView *)obj;
                aContentView.frame = CGRectMake(idx * self.bannerWidth, 0, self.bannerWidth, self.bannerHeight);
                [bannerContentView addSubview:aContentView];
            }
        }];
    
    return bannerContentView;
}

- (void)loopScroll {
    
    NSInteger bannerItemCount = self.contentViews.count;
    
    //循环滚动
    if (self.contentOffset.x > (bannerItemCount - 2) * self.bannerWidth) {
        
        [self setContentOffset:CGPointMake(self.bannerWidth, 0) animated:NO];
        
    }else if (self.contentOffset.x < self.bannerWidth){
        
        [self setContentOffset:CGPointMake((bannerItemCount - 2) * self.bannerWidth, 0) animated:NO];
        
    }
}

#pragma mark - event response

- (void)bannerTap:(UITapGestureRecognizer *) sender{
    
    if (!self.detailURLs || self.detailURLs.count <= 0) {
        
        return;
    }
    
    int index = (int)sender.view.tag - kTagBanner;
    
    NSString *contentURL = self.detailURLs[index];
    
    if (!contentURL || [contentURL isEqualToString:@""]) {
        return;
    }
}

- (void)pageCtlValueChange:(UIPageControl *) sender{

    //点击PageControll时，暂停定时器触发的自动滚动;
    self.timer.fireDate = [NSDate distantFuture];
    CGPoint point = self.contentOffset;
    point.x += self.bannerWidth;
    [UIView animateWithDuration:0.618 animations:^{
        self.contentOffset = point;
        
        [self loopScroll];
    }];
    
    //延时1秒后启动定时器
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        self.timer.fireDate = [NSDate distantPast];
    });
    
}

/**
 *  timer触发，banner滚动
 */
- (void)timerTriggerAutoScroll{
    
    if (self.isAutoScroll && self.pageCount > 1) {
        
        CGPoint point = self.contentOffset;
        point.x += self.frame.size.width;
        
        [UIView animateWithDuration:0.618 animations:^{
            
            self.contentOffset = point;
        }];
        
        [self loopScroll];
    }
}

#pragma mark - UIScrollViewDelegate

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    //滑动到监测结果页时，隐藏PageControll
    if (self.contentOffset.x == 2 * self.bannerWidth && self.hasMonitorResult) {
        
        self.pageControll.hidden = YES;
        
    }else{
        
        self.pageControll.hidden = NO;
        
    }
    
    //滑动时，切换PageControll的indicator
    NSInteger pageIndicate = self.contentOffset.x / self.bannerWidth + 0.5;
    self.pageControll.currentPage = pageIndicate - 1;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    [self loopScroll];
    
}

#pragma mark - getters

- (NSArray *)detailURLs{
    
    if (!_detailURLs) {
        
        _detailURLs = [NSArray array];
        
    }
    
    return _detailURLs;
}

- (NSArray *)bannerImgUrls{

    if (!_bannerImgUrls) {
        
        _bannerImgUrls = @[].copy;
    }
    
    return _bannerImgUrls;
}

- (UIPageControl *)pageControll{
    
    if (!_pageControll) {
        
        CGRect rect = self.frame;
        
        CGFloat pageCtlW = 0.5 * rect.size.width;
        CGFloat pageCtlH = 20.f;
        CGFloat pageCtlX = 0.25 * rect.size.width + rect.origin.x;
        CGFloat pageCtlY = rect.size.height - 20 + rect.origin.y;
        
        _pageControll = [[UIPageControl alloc] initWithFrame:CGRectMake(pageCtlX,pageCtlY,pageCtlW,pageCtlH)];
        self.pageControll.currentPage = 0;
        self.pageControll.currentPageIndicatorTintColor = kAPPThemeColor;
        self.pageControll.numberOfPages = self.pageCount;
        
        [self.pageControll addTarget:self action:@selector(pageCtlValueChange:) forControlEvents:UIControlEventValueChanged];
        
        self.pageControll.hidden = self.pageCount > 1 ? NO : YES;   //banner有两个滚动页以上，才显示UIPageControl
    }
    
    return _pageControll;
}

- (NSMutableArray *)contentViews{
    
    if (!_contentViews) {
        
        _contentViews = @[].mutableCopy;
        
    }
    
    return _contentViews;
}

- (NSMutableArray *)imgContentsMutableArr{
    
    if (!_imgContentsMutableArr) {
        
        _imgContentsMutableArr = @[].mutableCopy;
        
    }
    
    return _imgContentsMutableArr;
}

//- (YWKMonitorResultCOPDView *)monitorResultCOPDView{
//    
//    if (_monitorResultCOPDView == nil) {
//        
//        _monitorResultCOPDView = [[YWKMonitorResultCOPDView alloc] init];
//        
//        
//    }
//    
//    return _monitorResultCOPDView;
//}
//
//- (YWKMonitorResultOSASView *)monitorResultOSASView{
//    
//    if (!_monitorResultOSASView) {
//        
//        _monitorResultOSASView = [[YWKMonitorResultOSASView alloc] init];
//        
//    }
//    
//    return _monitorResultOSASView;
//}
//
//- (YWKMonitorResultCOPDView *)loopMonitorResultCOPDView{
//    
//    if (!_loopMonitorResultCOPDView) {
//        
//        _loopMonitorResultCOPDView = [[YWKMonitorResultCOPDView alloc] init];
//        
//    }
//    
//    return _loopMonitorResultCOPDView;
//}
//
//- (YWKMonitorResultOSASView *)loopMonitorResultOSASView{
//    
//    if (!_loopMonitorResultOSASView) {
//        
//        _loopMonitorResultOSASView = [[YWKMonitorResultOSASView alloc] init];
//        
//    }
//    
//    return _loopMonitorResultOSASView;
//}

#pragma mark - setters

//- (void)setMonitorResultType:(YWKMonitorResultType)monitorResultType{
//
//    
//    _monitorResultType = monitorResultType;
//    
//}

@end
